package cn.tedu._05weibo.controller;


import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLoginDto;
import cn.tedu._05weibo.pojo.dto.UserRegDto;
import cn.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("v1/users/")
@Api(tags = "01.用户模块")
public class UserController {
    @Autowired(required = false)
    private UserMapper  userMapper;


    @ApiOperation(value = "注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserRegDto userRegDto){
        log.debug("userRegDto="+userRegDto);
        String username=userRegDto.getUsername();
        UserVO userVO=userMapper.selectByUsername(username);
        log.debug("userVO="+userVO);
        if (userVO==null){
            int i = userMapper.insertUser(userRegDto);
            if (i==1)
                return  JsonResult.ok();
        }
        return new JsonResult(StatusCode.USERNAME_EXIST);
    }

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult Login(@RequestBody UserLoginDto userLoginDto,@ApiIgnore HttpSession session){
        String username=userLoginDto.getUsername();
        UserVO userVO=userMapper.selectByUsername(username);
        if (userVO!=null){
            if (userVO.getPassword().equals(userLoginDto.getPassword())){
                session.setAttribute("user",userVO);
                return  JsonResult.ok();
            }
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        }
        return new JsonResult(StatusCode.USERNAME_ERROR);
    }
    @ApiOperation(value = "查看当前用户功能")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVO userVO=(UserVO) (session.getAttribute("user"));
        return  new JsonResult(StatusCode.OPERATION_SUCCESS,userVO);
    }


    @ApiOperation(value = "退出登录")
    @GetMapping("logout")
    public JsonResult loginout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.ok();
    }
}
